Vue.js is a popular JavaScript framework that allows you to build dynamic and interactive user interfaces. One common task in web development is handling checkboxes and retrieving their values when a button is clicked. In this tutorial, we will demonstrate how to retrieve multiple checkbox values on button click in Vue.js using a simple example.
How to Retrieve Multiple Checkbox Values on Button Click in Vue js?
To get started, create a Vue.js app with a form that contains multiple checkboxes and a button. We use the v-for directive to dynamically render checkboxes based on an array of options. The v-model directive binds the checkbox values to an array called checkboxes.
<div id="app">
<form @submit.prevent="handleSubmit">
<label v-for="option in options" :key="option.value">
<input type="checkbox" :value="option.value" v-model="checkboxes" />
{{ option.label }}
</label>
<button type="submit">Submit</button>
</form>
<p v-if="selectedValues">Selected values: {{ selectedValues }}</p>
</div>
Retrieving Multiple Checkbox Values on Button Click in Vue js
In the Vue instance, we define the data properties: checkboxes
to store selected checkbox values and selectedValues
to display the selected values. The options
array holds the checkbox label and value pairs, making it easy to generate the checkboxes.
<script>
const app = new Vue({
el: "#app",
data: {
checkboxes: [],
selectedValues: '',
options: [
{ label: 'X', value: 'X' },
{ label: 'OpenAi', value: 'OpenAI' },
{ label: 'SchoolsGeek', value: 'SchoolsGeek' },
],
},
methods: {
handleSubmit() {
this.selectedValues = this.checkboxes.join(',');
},
},
});
</script>
Handling the Button Click Event
We create a method called handleSubmit
that will be triggered when the form is submitted. Inside this method, we join the selected checkbox values into a comma-separated string and assign it to the selectedValues
property
Conclusion
In Vue.js, retrieving multiple checkbox values on button click is a straightforward process. By using data binding and Vue’s reactivity, we can easily track and display the selected values. This tutorial provides you with a clear example of how to achieve this functionality in your Vue.js applications.